package org.flint92.springcloud.hystrix.rxjava;

import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Single;
import rx.schedulers.Schedulers;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author flint92
 */
public class RxJavaDemo {

    public static void main(String[] args) throws InterruptedException {

//        singleDemo();

//        observableDemo();

        standardReactive();

        TimeUnit.MILLISECONDS.sleep(200);
    }

    static void standardReactive() {
        final List<Integer> integers = ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Observable.from(integers) // 发布多个数据
                .subscribeOn(Schedulers.newThread())
                .subscribe(value -> {
                            if (value > 4) {
                                throw new IllegalArgumentException("value expected less equal than 4, but actual is " + value);
                            }
                            // 消费数据
                            println("consumer data: " + value);
                        },
                        e -> {
                            // 异常
                            println("consumer error. " + e.getLocalizedMessage());
                        },
                        () -> {
                            // 整个流程完成
                            println("consumer finish.");
                        })
        ;
    }

    static void observableDemo() {
        final List<Integer> integers = ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Observable.from(integers) // 发布多个数据
                .subscribeOn(Schedulers.computation())
                .subscribe(RxJavaDemo::println) // 订阅并且消费数据
        ;
    }

    static void singleDemo() {
        Single.just("Hello World!") // just仅能发布单个数据
                .subscribeOn(Schedulers.io())
                .subscribe(RxJavaDemo::println) // 订阅并且消费数据
        ;
    }

    static void println(Object value) {
        System.out.printf("[Thread: %s] value: %s\n", Thread.currentThread().getName(), value);
    }

}
